package com.example.music_admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.music_admin.entity.Singer;
import com.example.music_admin.entity.Singer;
import com.example.music_admin.service.ISingerService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 歌手 前端控制器
 * </p>
 *
 * @author jerry
 * @since 2025-09-10
 */
@RestController
@RequestMapping("/singer")
public class SingerController {

    //获取业务层的对象
    @Autowired  //自动注入
    private ISingerService singerService;

    //    提供json的解析工具
    ObjectMapper jsonTool = new ObjectMapper();

    //根据name进行模糊查询
    //获取所有用户 http://localhost:8085/music/singer/list?pageNum=2&size=4
    @RequestMapping("/list")
    public String list(@RequestParam(required = false, defaultValue = "") String name,
                       @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(required = false, defaultValue = "4") Integer size) throws JsonProcessingException {
        //定义map键值对的集合
        HashMap<String, Object> result = new HashMap<>();
        //构建条件构造器
        QueryWrapper<Singer> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(name != null && !name.equals(""), "name", name);
        //构建分页对象
        IPage<Singer> page = new Page<>(pageNum, size);
        //1、调用业务层方法查询\注入queryWrapper
        IPage<Singer> singerIPage = singerService.page(page, queryWrapper);
        List<Singer> list = singerIPage.getRecords();
        result.put("list", list);
        result.put("total", singerIPage.getTotal());
        //2、返回json格式的数据
        return jsonTool.writeValueAsString(result);
    }


}
